package com.ihelp.controller;

import com.ihelp.annotation.UserCheckLogin;
import com.ihelp.entities.CommonResult;
import com.ihelp.pojo.Order;
import com.ihelp.pojo.User;
import com.ihelp.service.OrderService;
import com.ihelp.service.UserService;
import com.ihelp.util.CookieUtil;
import com.ihelp.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author LiuZiMing
 * @since 2023-05-23
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    @Value("${ihelp.path.headSculpture}")
    public String headSculptureFilePrefix;

    @GetMapping("/all")
    public CommonResult getAllUser() {
        List<User> allUser = userService.getAllUser();
        return new CommonResult<>(200, "获取所有用户成功", allUser);

    }

    @GetMapping("/id/{id}")
    public CommonResult getUserById(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        if (user != null) {
            return new CommonResult<>(200, "根据id：" + id + ",获取对应用户成功", user);
        } else {
            return new CommonResult(204, "根据id：" + id + ",未找到对应用户");
        }
    }

    @PostMapping("/")
    public CommonResult createUser(@RequestParam("nickname") String nickname, @RequestParam("file") MultipartFile file, @RequestParam("username") String username,
                                   @RequestParam("password") String password, @RequestParam("area") String area, @RequestParam("phoneNumber") Long phoneNumber,
                                   @RequestParam("birthday") String birthday, @RequestParam("personalIntroduction") String personalIntroduction)
            throws Exception {
        List<User> userByDynamicConditions = userService.getUserByDynamicConditions(null, null, null, username,
                null, null, null, null, null, null, null, null, null, null);
        System.out.println(userByDynamicConditions);
        if(userByDynamicConditions.isEmpty()){
            String uuid0 = UUID.randomUUID().toString().replace("-", "");
            // 2 获取原始的文件名
            String headSculptureDocumentName = file.getOriginalFilename();
            // 3 先截取原文件的文件名后缀
            String headSculptureSuffix = headSculptureDocumentName.substring(headSculptureDocumentName.lastIndexOf("."), headSculptureDocumentName.length());
            //            新图像文件名
            String headSculptureNewDocumentName = uuid0 + headSculptureSuffix;
            //        获取新图片路径
            String pictureUrl = headSculptureFilePrefix + headSculptureNewDocumentName;
            //文件复制
            File newFile = new File(pictureUrl);
            newFile.getParentFile().mkdir();
            file.transferTo(newFile);

            Integer result = userService.createUser(nickname, headSculptureNewDocumentName, username, password, area, phoneNumber, birthday, personalIntroduction);
            if (result != null && 1 == result) {
                User user = userService.getUserByUsernameAndPassword(username, password);
                String userJWT = "";
                if (user != null) {
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("id", user.getId());
                    userJWT = jwtUtil.createJWT(uuid, "IHelp", 0L, map);
                }
                return new CommonResult<>(200, "插入用户数据成功",userJWT);
            } else {
                return new CommonResult(400, "插入用户数据失败");
            }
        }else {
            return new CommonResult(400, "用户名重复，请重试");
        }

    }


    @GetMapping("/username/password")
    public CommonResult getUserByUsernameAndPassword(@RequestParam("username") String username,
                                                     @RequestParam("password") String password
    ) {
        User user = userService.getUserByUsernameAndPassword(username, password);
        if (user != null) {
            return new CommonResult<>(200, "获取用户成功", user);
        } else {
            return new CommonResult<>(204, "账号密码错误");
        }
    }

    @GetMapping("/login")
    public CommonResult userLogin(@RequestParam("username") String username,
                                  @RequestParam("password") String password
    ) throws Exception {
        User user = userService.getUserByUsernameAndPassword(username, password);
        if (user != null) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            String userJWT = jwtUtil.createJWT(uuid, "IHelp", 0L, map);
            return new CommonResult<>(200, "登录成功,请保存用户登录信息", userJWT);
        } else {
            return new CommonResult<>(204, "账号或密码错误");
        }
    }

    @UserCheckLogin
    @GetMapping("/checkLogin")
    public CommonResult checkJWT(HttpServletRequest req) {
        try {
            String userJWT = CookieUtil.getCookies(req, "userJWT");
            Claims claims = jwtUtil.parseJWT(userJWT);
            Integer userId = claims.get("id", Integer.class);
            User userById = userService.getUserById(userId);
            return new CommonResult(200, "验证成功",userById);
        } catch (Exception e) {
            return new CommonResult(401, "用户验证信息错误");
        }
    }

    

}
